from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from QQLoginTool.QQtool import OAuthQQ
from mall import settings
from .models import OauthQQUser
# Create your views here.


class QQauthURLView(APIView):

    def get(self,request):

        state = request.query_params.get('state')
        if not state:
            state = '/'

        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state=state)

        login_url = oauth.get_qq_url()

        return Response({'auth_url':login_url})

from rest_framework import status
from utils.public import CreateToken
from .utils import generate_safe_token
from rest_framework.generics import GenericAPIView
from .serializers import QQauthUserSerializer
class QQauthUserView(GenericAPIView):

    serializer_class = QQauthUserSerializer

    def get(self,request):
        code =request.query_params.get('code')

        if not code:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI)

        try:
            access_token = oauth.get_access_token(code)
            openid = oauth.get_open_id(access_token)
        except Exception:
            return Response(status=status.HTTP_503_SERVICE_UNAVAILABLE)

        #根据openid查询用户是否在本站注册过
        try:
            qq_user = OauthQQUser.objects.get(openid=openid)
        except OauthQQUser.DoesNotExist:
            # 1.没注册，将openid返回给前端做绑定注册处理
            token = generate_safe_token(openid)
            return Response({'access_token':token})

        else:
            #2.注册过，生成token信息返回给前端
            token = CreateToken(qq_user)
            data = {
              'token':token,
              'username':qq_user.user.username,
              'id':qq_user.user.id
            }
            return Response(data)

    def post(self,request):
        """
        access_token:"eyJleHAiOjE1NTEwMTcxOTYsImFsZyI6IkhTMjU2IiwiaWF0IjoxNTUxMDEzNTk2fQ.eyJvcGVuaWQiOiJBNjU2RUM0NDA0MzkxODM4QkU2RDFEMkEwNTk2Qzg4QSJ9.2E4EBokB1RNWw-UqAExY1Plp1bjl3hs1f1w1auwpi7c"
        mobile:"17640380300"
        password:"1234567890"
        sms_code:"239632"
        """
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()

        token = CreateToken(user)
        data = {
            'token':token,
            'username':user.username,
            'id':user.id
        }
        return Response(data)






